<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <!-- 绑定监听器方式一 -->
      <!-- <TodoHeader @addTodo="addTodo" /> -->
      <!-- 绑定监听器方式二 -->
      <TodoHeader ref="addTodo" />
      <TodoList :todos="todos" />
      <TodoFooter>
        <template v-slot:allCheck>
          <input type="checkbox" v-model="isAllCheck" />
        </template>
        <template v-slot:count>
          <span><span>已完成{{ completeNum }}</span> / 全部{{ todos.length }}</span>
        </template>
        <template v-slot:clear>
          <button v-show="completeNum" @click="delCompleteTodos" class="btn btn-danger">清除已完成任务</button>
        </template>
      </TodoFooter>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import storageUtil from './util/storageUtil.js'
import TodoHeader from './components/TodoHeader.vue'
import TodoList from './components/TodoList.vue'
import TodoFooter from './components/TodoFooter.vue'

export default {
  data () {
    return {
      todos: storageUtil.readTodos()
    }
  },
  mounted () {
    // 编程式给组件绑定事件监听器
    this.$refs.addTodo.$on('addTodo', this.addTodo)
    // 订阅消息
    PubSub.subscribe('delTodo', (msg, index) => {
      this.delTodo(index)
    })
  },
  methods: {
    addTodo (todo) {
      this.todos.unshift(todo)
    },
    delTodo (index) {
      this.todos.splice(index, 1)
    },
    delCompleteTodos () {
      this.todos = this.todos.filter(item => !item.complete)
    },
    selectAllTodos (check) {
      this.todos.forEach(item => {
        item.complete = check
      })
    }
  },
  watch: {
    todos: {
      deep: true, // 深度监视
      // handler: function (newVal) {
      //   storageUtil.saveTodos(newVal)
      // }
      handler: storageUtil.saveTodos
    }
  },
  computed: {
    completeNum () {
      return this.todos.reduce(function (preTotal, cur) {
        return preTotal + (cur.complete ? 1 : 0)
      }, 0)
    },
    isAllCheck: {
      get () {
        return this.completeNum === this.todos.length && this.completeNum > 0
      },
      set (value) {
        this.selectAllTodos(value)
      }
    }
  },
  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  }
}
</script>

<style>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
